package common.spring.jdbc;

import common.pojo.Page;
import org.springframework.dao.EmptyResultDataAccessException;

import java.util.List;
import java.util.Map;

/**
 * Created by luozongsheng on 12/20/16.
 */
public class MySQLHelper extends SQLHelper {

    public <T> Page<T> queryForPageBean(String sql, Class<T> type, int curPage, int pageSize){
        return queryForPageBean(sql,new Object[0],type,curPage,pageSize);
    }

    public <T> Page<T> queryForPageBean(String sql, Object[] params, Class<T> type, int curPage, int pageSize){
        Page page=new Page();
        String totalSql= String.format("select count(*) from ( %s ) a",sql);
        String pageSql= String.format(" %s limit %s,%s",sql,(curPage-1)*pageSize,pageSize);
        Integer count=jdbcTemplate.queryForObject(totalSql,Integer.class,params);
        List<T> resultList;
        if(type==Map.class){
            resultList=(List<T>)queryForListMap(pageSql,params);
        }else{
            resultList=queryForListBean(pageSql,type,params);
        }
        page.setResult(resultList);
        page.setTotalCount(count);
        page.setCurPage(curPage);
        page.setPageSize(pageSize);
        return page;
    }

    public Map<String,Object> queryForPageWithMap(String sql, Object[] params, int curPage, int pageSize){
        String pageSql= String.format(" %s limit %s,%s",sql,(curPage-1)*pageSize,pageSize);
        try{
            return jdbcTemplate.queryForMap(pageSql,params);
        }catch (EmptyResultDataAccessException e){
            return null;
        }
    }
}
